﻿using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;

namespace Cms.Application.Admin.Presenters
{
    public class AdminMasterPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IAdminMasterView _view;

        public IUpdater Updater { get; set; }

        public AdminMasterPresenter(IAdminMasterView view)
            : this(view, new RepositoryFactory())
        {
            Updater = new Updater();
        }

        public AdminMasterPresenter(IAdminMasterView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            _view.SetAdministratorName(_administrator.Fullname);
            _view.SetSystemCulture(_administrator);
        }
        
        public void Initialize()
        {
            _view.SetCurrentSite(_administrator.CurrentSite.Domain);
            _view.SetSystemVersion(Updater.GetCurrentVersion().Full);
            if (_administrator.ShowIntroHelp && !_view.IntroHelpDisplayed)
            {
                _view.ShowIntroHelp();
            }
        }

        public void GetAvailableSites()
        {
            _view.SetAvailableSites(_administrator.AvailableSites);
        }

        public string SetCurrentSite(int id)
        {
            _administrator.CurrentSite = SiteRepository.GetSite(id);
            _administrator.CurrentSiteLocale = _administrator.CurrentSite.DefaultLocale;
            AdministratorRepository.SaveAdministrator(_administrator);
            return _administrator.CurrentSite.Domain;
        }
        
        public void SetCurrentLocalization(string localizationCode)
        {
            _administrator.DefaultSystemLocale = localizationCode;
            AdministratorRepository.SaveAdministrator(_administrator);
        }
        
        public void LogVisitedAdminUrl(string url, string header, string imageUrl)
        {
            _administrator.LogVisitedAdminUrl(url, header, imageUrl);
            AdministratorRepository.SaveAdministrator(_administrator);
        }
        
        public void ToggleShowIntroHelp()
        {
            _administrator.ShowIntroHelp = !_administrator.ShowIntroHelp;
            AdministratorRepository.SaveAdministrator(_administrator);
        }
    }
}